package cn.leftshine.myithome.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

import cn.leftshine.myithome.R;
import cn.leftshine.myithome.adapter.MyNewsRecyclerViewAdapter;
import cn.leftshine.myithome.beans.NewsItem;
import cn.leftshine.myithome.utils.RssParseTool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class NewsListFragment extends Fragment {

    // TODO: Customize parameter argument names
    public static final int MSG_XML_PARSE_COMPLETE = 1001;
    private static final String ARG_COLUMN_COUNT = "column-count";

    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;
    private LinearLayout ll_main_bottom;
    private boolean isBottomShow=true;
    private String title;
    private List<NewsItem> newsItems = new ArrayList<>();
    private MyNewsRecyclerViewAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public NewsListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static NewsListFragment newInstance(int columnCount) {
        NewsListFragment fragment = new NewsListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
            title = getArguments().getString("title");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);

        // Set the adapter
        if (view instanceof SwipeRefreshLayout) {
            Context context = view.getContext();
            swipeRefreshLayout = (SwipeRefreshLayout) view;
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    initListData(title);
                }
            });
            RecyclerView recyclerView = swipeRefreshLayout.findViewById(R.id.news_list);
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }

            adapter = new MyNewsRecyclerViewAdapter(newsItems, mListener,getContext().getApplicationContext());
            recyclerView.setAdapter(adapter);

            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    ll_main_bottom=getActivity().findViewById(R.id.ll_main_bottom);

                    //上滑 并且 正在显示底部栏
                    if (dy > 0 && isBottomShow) {
                        isBottomShow = false;
                        //将Y属性变为底部栏高度  (相当于隐藏了)
                        ll_main_bottom.animate().translationY(ll_main_bottom.getHeight());
                    } else if (dy < 0 && !isBottomShow) {
                        isBottomShow = true;
                        ll_main_bottom.animate().translationY(0);
                    }
                    super.onScrolled(recyclerView, dx, dy);
                }
            });
            DividerItemDecoration decoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
            recyclerView.addItemDecoration(decoration);
        }
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipeRefreshLayout.setRefreshing(true);
        initListData(title);
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(NewsItem item);
    }

    private void initListData(String title) {
        if("最新"==title){
           String rssSrc = "https://www.ithome.com/rss/";
           sendRequestWithOkHttp(rssSrc);
            /*URL rssSrc = null;
            try {
                rssSrc = new URL("https://www.ithome.com/rss/");
            } catch (MalformedURLException e) {
                Log.e("pcj", "initListData: URL转换错误" );
                e.printStackTrace();
            }
            RssParseTool rssParseTool = new RssParseTool(rssSrc);*/

        }
    }

    public void sendRequestWithOkHttp(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    RssParseTool rssParseTool = new RssParseTool();
                    rssParseTool.parseXMLWithPull(responseData,newsHandler);
                    //showList(newsItems);
                }catch (Exception e){
                    Log.e("pcj", "sendRequestWithOkHttp fail");
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void showList(final List<NewsItem> newsItems) {
        /*getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.update(newsItems);
            }
        });*/
        //adapter.update(newsItems);

    }
     private Handler newsHandler = new Handler(){
         @Override
         public void handleMessage(Message msg) {
             switch (msg.what){
                 case MSG_XML_PARSE_COMPLETE:
                     newsItems = (List<NewsItem>) msg.obj;
                     adapter.update(newsItems);
                     swipeRefreshLayout.setRefreshing(false);
                     break;
             }
         }
     };

}
